package com.etooling.pdm.controller;

import com.etooling.framework.jpa.JpaQueryBuilder;
import com.etooling.framework.jpa.Sorts;
import com.etooling.framework.jpa.Specifications;
import com.etooling.framework.svo.ReplyObj;
import com.etooling.framework.utils.WebUtils;
import com.etooling.pdm.dto.GoodsPageDTO;
import com.etooling.pdm.entity.Goods;
import com.etooling.pdm.entity.GoodsSpecs;
import com.etooling.pdm.entity.GoodsType;
import com.etooling.pdm.repository.*;
import com.etooling.pdm.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping(value = "/admin/pdm/goods")
@Controller
@EnableAutoConfiguration
public class GoodsController {

    @Autowired
    private GoodsRepository goodsRepository;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    GoodsTypeRepository goodsTypeRepository;
    @Autowired
    GoodsPropValuesRepository goodsPropValuesRepository;
    @Autowired
    GoodsPropSettingRepository goodsPropSettingRepository;
    @Autowired
    GoodsSpecsRepository goodsSpecsRepository;


    @RequestMapping("pageQueryGoodsAndProp") // 查询
    @ResponseBody
    ReplyObj pageQueryGoodsAndProp(HttpServletRequest request,
                                   @RequestParam(defaultValue = "20", required = false, value = "pageSize") int pageSize,
                                   @RequestParam(defaultValue = "1", required = false, value = "page") int page,
                                   @RequestParam(defaultValue = "", required = false, value = "goodsTypeId") String goodsTypeId
    ) {
        Map<String, Object> returnMap = new HashMap<>();

        JpaQueryBuilder pb = Specifications.<Goods>and();
        pb.predicate(Specifications.or().eq("status", Goods.STATUS_IS_RUN).isNull("status").build());
        String companyId = WebUtils.getSessionValue(request, WebUtils.LOGIN_COMPANY_ID_KEY);
        pb.eq("companyId", companyId);
        if (WebUtils.checkStr(goodsTypeId)) {
            pb.eq("goodsType.id", goodsTypeId);
        }
        Specification<Goods> spec = pb.build();

        Sort sort = Sorts.builder().desc("createTime").build();

        Pageable pageable = PageRequest.of(page - 1, pageSize, sort);
        Page<Goods> goodsPage = goodsRepository.findAll(spec, pageable);
        List<GoodsPageDTO> dtoList = new ArrayList<>();
        for (Goods goods : goodsPage.getContent()) {
            GoodsPageDTO goodsPageDTO = new GoodsPageDTO();
            if (goods.getCreator() != null) {
                goodsPageDTO.setCreatorName(goods.getCreator().getName());
                goodsPageDTO.setCreatorId(goods.getCreator().getId());
            }
            goodsPageDTO.setCreateTime(goods.getCreateTime());
            if (goods.getModifier() != null) {
                goodsPageDTO.setModifierName(goods.getModifier().getName());
                goodsPageDTO.setModifierId(goods.getModifier().getId());
            }
            goodsPageDTO.setLastModifiedTime(goods.getLastModifiedTime());
            if (goods.getGoodsType() != null) {
                GoodsType oldType = goods.getGoodsType();
                GoodsType goodsType = new GoodsType();
                goodsType.setId(oldType.getId());
                goodsType.setTypeName(oldType.getTypeName());
                goodsType.setTypeCode(oldType.getTypeCode());
                goodsType.setParentId(oldType.getParentId());
                goodsType.setSeq(oldType.getSeq());
                goodsType.setStatus(oldType.getStatus());
                goodsType.setIsProduct(oldType.getIsProduct());
                goodsType.setIsComponents(oldType.getIsComponents());
                goodsType.setTypeNamePath(oldType.getTypeNamePath());
                goodsType.setTypeCodePath(oldType.getTypeCodePath());
                goodsType.setCompanyId(oldType.getCompanyId());
                goodsPageDTO.setGoodsType(goodsType);
            }
            goodsPageDTO.setId(goods.getId());
            goodsPageDTO.setMaterialCode(goods.getMaterialCode());
            goodsPageDTO.setName(goods.getName());
            goodsPageDTO.setReqGoodsName(goods.getReqGoodsName());
            goodsPageDTO.setUnit(goods.getUnit());
            goodsPageDTO.setMemo(goods.getMemo());
            goodsPageDTO.setStatus(goods.getStatus());
            goodsPageDTO.setCompanyId(goods.getCompanyId());
            goodsPageDTO.setImgId(goods.getImgId());
            goodsPageDTO.setImgUrl(goods.getImgUrl());
            goodsPageDTO.setGoodsNamesPath(goods.getGoodsNamesPath());
            goodsPageDTO.setGoodsCodesPath(goods.getGoodsCodesPath());
            dtoList.add(goodsPageDTO);
        }
        Page<GoodsPageDTO> dtoPage = new PageImpl<>(dtoList, goodsPage.getPageable(), goodsPage.getTotalElements());

        returnMap.put("goodsPage", dtoPage);

        //获取属性，因为不同的分类下属性不同，所以参数值不同，如果分类为空，所有分类时，就不带规格属性了。
        //拿出列头,先做单级,之后再优化成连到子的分类一并拿出来。
        if (WebUtils.checkStr(goodsTypeId)) {
            List<Map<String, Object>> idAndName = goodsPropSettingRepository.getIdAndName(goodsTypeId);
            returnMap.put("goodsPropSettings", idAndName);

            //分页的产品组装id列表，一次查出，减少sql操作次数
            List<String> goodsIds = new ArrayList<>();
            for (Goods goods : goodsPage.getContent()) {
                goodsIds.add(goods.getId());
            }

            List<Map<String, Object>> infoByGoodsTypeId = goodsPropValuesRepository.getInfoByGoodsId(goodsIds);

            Map<String, Map<String, Map<String, Object>>> propValues = new HashMap<>();
            for (Map<String, Object> map : infoByGoodsTypeId) {
                String goodsId = (String) map.get("goods_id");
                Map<String, Map<String, Object>> goodsIdsMap = propValues.get(goodsId);
                if (goodsIdsMap == null) {
                    goodsIdsMap = new HashMap<>();
                    propValues.put(goodsId, goodsIdsMap);
                }
                String settingId = (String) map.get("setting_id");
                goodsIdsMap.put(settingId, map);
            }

            returnMap.put("goodsPropValuesMap", propValues);
        }

        return WebUtils.flushSuccess(returnMap);
    }


    @RequestMapping("addGoods")
    @ResponseBody
    ReplyObj addGoods(HttpServletRequest request, @RequestParam(defaultValue = "", required = false, value = "json") String json) {
        return goodsService.addGoods(request, json);
    }


    @RequestMapping("updateGoods")
    @ResponseBody
    ReplyObj updateGoods(HttpServletRequest request, @RequestParam(defaultValue = "", required = false, value = "json") String json) {
        return goodsService.updateGoods(request, json);
    }


    @RequestMapping("delGoods")
    @ResponseBody
    ReplyObj delGoods(HttpServletRequest request, @RequestParam(defaultValue = "", required = false, value = "id") String id) {
        return goodsService.delGoods(request, id);
    }


    /**
     * 用于去修改产品
     *
     * @param request
     * @param goodsTypeId
     * @param goodsId
     * @return
     */
    @RequestMapping("toEdit")
    @ResponseBody
    ReplyObj toEdit(HttpServletRequest request,
                    @RequestParam(defaultValue = "", required = false, value = "goodsTypeId") String goodsTypeId,
                    @RequestParam(defaultValue = "", required = false, value = "goodsId") String goodsId) {
        Map map = new HashMap();

        if (WebUtils.checkStr(goodsTypeId)) {
            List<Map<String, Object>> propList = goodsPropSettingRepository.getPropList(goodsTypeId, goodsId);
            map.put("propList", propList);
        }

        JpaQueryBuilder pb = Specifications.<GoodsSpecs>and();
        pb.eq("goods.id", goodsId);
        long count = goodsSpecsRepository.count(pb.build());
        map.put("specsCount", count);

        return WebUtils.flushSuccess(map);
    }


}
